use mongodb::{
    bson::doc,
    options::{ClientOptions, ServerApi, ServerApiVersion},
    Client, Collection,
};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    sex: String,
}

// 增删改查 -> 写入操作
// 1. insert_one() 插入一个文档
#[allow(dead_code)]
async fn mongo_insert_one(client: &Client, name: &str, sex: &str) -> mongodb::error::Result<()> {
    let my_coll: Collection<User> = client.database("fly-test").collection("users");
    let doc = User {
        name: name.to_string(),
        sex: sex.to_string(),
    };

    let insert_one_result = my_coll.insert_one(doc, None).await?;
    println!(
        "Inserted document with _id: {}",
        insert_one_result.inserted_id
    );

    Ok(())
}

// 2. insert_many() 插入一个或多个文档
#[allow(dead_code)]
async fn mongo_insert_many(client: &Client, docs: Vec<User>) -> mongodb::error::Result<()> {
    let my_coll: Collection<User> = client.database("fly-test").collection("users");

    let insert_many_result = my_coll.insert_many(docs, None).await?;
    println!("Inserted documents with _ids:");
    for (_key, value) in &insert_many_result.inserted_ids {
        println!("{:?}", value);
    }
    Ok(())
}

#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
    let uri = "mongodb://localhost:27017";
    let mut client_options = ClientOptions::parse_async(uri).await?;

    let server_api = ServerApi::builder().version(ServerApiVersion::V1).build();
    client_options.server_api = Some(server_api);

    let client = Client::with_options(client_options)?;

    client
        .database("admin")
        .run_command(doc! { "ping": 1 }, None)
        .await?;
    println!("Pinged your deployment. You successfully connected to MongoDB!");

    Ok(())
}
